package com.capinfo.accumulation.web.controller.collection;

import com.capinfo.accumulation.model.collection.Company;
import com.capinfo.accumulation.model.collection.Freeze;
import com.capinfo.accumulation.parameter.collection.FreezeParameter;
import com.capinfo.accumulation.service.collection.FreezeService;
import com.capinfo.commons.project.model.security.SystemUser;
import com.capinfo.accumulation.web.Constants;
import com.capinfo.commons.project.utils.JsonUtils;
import com.capinfo.commons.project.web.controller.manage.region.RegionManageController;
import com.capinfo.framework.model.dictionary.Dictionary;
import com.capinfo.framework.service.CommonsDataOperationService;
import com.capinfo.framework.util.IOUtils;
import com.capinfo.framework.util.LogUtils;
import com.capinfo.framework.web.controller.CommonsDataManageController;
import com.capinfo.framework.web.util.ControllerUtils;
import com.capinfo.framework.web.util.WebRequestUtils;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.ModelAndView;

import java.io.OutputStream;

import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by thinkpadwyl on 2017/10/19.
 */
@Controller
@RequestMapping("/business/collection/freeze")
public class FreezeController extends CommonsDataManageController<FreezeParameter, Freeze> {
    private static final Log logger = LogFactory.getLog(RegionManageController.class);
    //注入
    @Autowired
    private FreezeService freezeService;

    /**
     * 征信信息是否存在
     * @param request
     * @param parameter
     * @param stream
     * @return
     */
    @RequestMapping("/is_exist.shtml")
    @ResponseBody
    public String isExist(NativeWebRequest request, FreezeParameter parameter, OutputStream stream){
        WebRequestUtils.setCharacterEncodingForUTF8(request);
        WebRequestUtils.setContentTypeForHTML(request);

        JSONObject json = new JSONObject();
        if(null == parameter.getIdNumber()) {
            json.put("result", false);
            json.put("errCode", 0L);
            json.put("errMsg", "查无此人");

        }else{
            //TODO 调用征信系统
            json.put("result", true);
            json.put("errCode", 1L);
            json.put("errMsg", "");
        }
        return json.toString();
    }


    /**
     * 冻结审核调用
     * @param request
     * @param parameter
     * @param stream
     */
    @RequestMapping("/freezeAudit.shtml")
    public void freezeAudit(NativeWebRequest request, FreezeParameter parameter, OutputStream stream){

        boolean isAudit = freezeService.freezeAudit(parameter);
        //todo 调用个人公积金冻结接口
        JSONObject json = new JSONObject();
        json.put("result", isAudit);

        try {
            IOUtils.outputByStream(stream, json.toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            LogUtils.debugException(logger, e);
        }
    }

    /**
     * 解冻审核调用
     * @param request
     * @param parameter
     * @param stream
     */
    @RequestMapping("/unfreezeAudit.shtml")
    public void unfreezeAudit(NativeWebRequest request, FreezeParameter parameter, OutputStream stream){

        boolean isAudit = freezeService.unfreezeAudit(parameter);
        //todo 调用个人公积金解冻接口
        JSONObject json = new JSONObject();
        json.put("result", isAudit);

        try {
            IOUtils.outputByStream(stream, json.toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            LogUtils.debugException(logger, e);
        }
    }

    /**
     * 延期调用
     * @param request
     * @param parameter
     * @param stream
     * @return
     */
    @RequestMapping("/delay.shtml")
    @ResponseBody
    public String delay(NativeWebRequest request, FreezeParameter parameter, OutputStream stream){
        boolean isDelay = freezeService.delay(parameter);
        JSONObject json = new JSONObject();
        json.put("result", isDelay);
        return json.toString();
    }

    /**
     * 解冻调用
     * @param request
     * @param parameter
     * @param stream
     * @return
     */
    @RequestMapping("/unfreeze.shtml")
    @ResponseBody
    public String unfreeze(NativeWebRequest request, FreezeParameter parameter, OutputStream stream){
        boolean unfreeze = freezeService.unfreeze(parameter);
        JSONObject json = new JSONObject();
        json.put("result", unfreeze);
        return json.toString();
    }

    /**
     * 是否能解冻
     * @param request
     * @param parameter
     * @param stream
     * @return
     */
    @RequestMapping("/CanUnfreeze.shtml")
    @ResponseBody
    public String isUnfreeze(NativeWebRequest request, FreezeParameter parameter, OutputStream stream){
        Freeze freeze = freezeService.getObjectById(parameter);
        boolean isUnfreeze = false;
        if(freeze != null)
        {
           Long state =  freeze.getState();
            if(state == 1L)
                isUnfreeze = true;
        }
        JSONObject json = new JSONObject();
        json.put("result", isUnfreeze);
        return json.toString();
    }

    /**
     * 是否能解冻审核
     * @param request
     * @param parameter
     * @param stream
     * @return
     */
    @RequestMapping("/CanUnfreezeAudit.shtml")
    @ResponseBody
    public String isUnfreezeAudit(NativeWebRequest request, FreezeParameter parameter, OutputStream stream){
        Freeze freeze = freezeService.getObjectById(parameter);
        boolean isUnfreeze = false;
        if(freeze != null)
        {
            Long state =  freeze.getState();
            if(state == 2L)
                isUnfreeze = true;
        }
        JSONObject json = new JSONObject();
        json.put("result", isUnfreeze);
        return json.toString();
    }

    /**
     * 解冻审核界面调用
     * @param request
     * @param parameter
     * @return
     */
    @RequestMapping("/examine.shtml")
    public final Map<String, Object> examine(NativeWebRequest request, FreezeParameter parameter){
        if(this.formBeforeInvoke(request, parameter)) {
            this.getCommonsDataOperationService().populateParameter(parameter);
        }

        Map<String, Object> viewModel = ControllerUtils.buildViewModel(parameter);
        return this.formAfterInvoke(request, parameter, viewModel);
    }

    /**
     * 冻结申请保存
     * @param request
     * @param parameter
     * @param writer
     */
    @RequestMapping({"/save_or_update.shtml"})
    public void saveOrUpdate(NativeWebRequest request, FreezeParameter parameter, Writer writer) {
        parameter = this.saveOrUpdateBeforeInvoke(request, parameter);
        if(parameter == null) {
            ControllerUtils.outputByWriter(request, writer, false);
        } else {
            Freeze entity = this.getCommonsDataOperationService().saveOrUpdate(parameter);
            this.saveOrUpdateAfterInvoke(request, parameter, entity);
            boolean token = entity == null ? false : true;
            if (token) {
                JSONObject json = new JSONObject();
                json.put("id", entity.getId());
                json.put("result", true);


                ControllerUtils.outputByWriter(request, writer, json.toString());

            } else {
                ControllerUtils.outputByWriter(request, writer, entity != null);
            }
        }
    }

    /**
     * 冻结入口
     * @param parameter
     * @return
     */
    @RequestMapping({"/search.shtml"})
    public Map<String, Object> search(FreezeParameter parameter) {

        Map<String, Object> viewModel = ControllerUtils.buildViewModel(parameter);
        Set<Dictionary> regionList = freezeService.getDictionariesBySortName("区县");
        viewModel.put("regionList",regionList);
        Set<Dictionary> siteList = freezeService.getDictionariesBySortName("缴存网点");
        viewModel.put("siteList",siteList);
        return viewModel;
    }

    /**
     * 解冻入口
     * @param parameter
     * @return
     */
    @RequestMapping({"/thaw_search.shtml"})
    public Map<String, Object> thawSearch(FreezeParameter parameter) {
        Map<String, Object> viewModel = ControllerUtils.buildViewModel(parameter);
        Set<Dictionary> regionList = freezeService.getDictionariesBySortName("区县");
        viewModel.put("regionList",regionList);
        Set<Dictionary> siteList = freezeService.getDictionariesBySortName("缴存网点");
        viewModel.put("siteList",siteList);
        return viewModel;
    }



    protected Map<String, Object> formAfterInvoke(NativeWebRequest request,FreezeParameter parameter, Map<String, Object> viewModel) {
        viewModel.put("freezeFlag",parameter.getFreezeFlag());
        Set<Dictionary> freezeReasonList = freezeService.getDictionariesBySortName("冻结原因");
        viewModel.put("freezeReasonList",freezeReasonList);
        Set<Dictionary> unfreezeReasonList = freezeService.getDictionariesBySortName("解冻原因");
        viewModel.put("unfreezeReasonList",unfreezeReasonList);
        Set<Dictionary> courtNameList = freezeService.getDictionariesBySortName("法院名称");
        viewModel.put("courtNameList",courtNameList);
        Set<Dictionary> siteList = freezeService.getDictionariesBySortName("缴存网点");
        viewModel.put("siteList",siteList);
        Set<Dictionary> regionList = freezeService.getDictionariesBySortName("区县");
        viewModel.put("regionList",regionList);

        return viewModel;
    }

    /**
     * 获取解冻服务
     * @return
     */
    @Override
    public CommonsDataOperationService<Freeze, FreezeParameter> getCommonsDataOperationService() {

        return freezeService;
    }

    /**
     * 保存前处理
     * @param request
     * @param parameter
     * @return 冻结参数
     */
    @Override
    protected FreezeParameter saveOrUpdateBeforeInvoke(NativeWebRequest request, FreezeParameter parameter) {

        SystemUser user  = (SystemUser)WebRequestUtils.retrieveSessionAttribute( request, Constants.ADMIN_ATTRIBUTE_KEY);
        Company company = (Company) WebRequestUtils.retrieveSessionAttribute(request, Constants.COMPANY_BINDING_ATTRIBUTE_KEY);
        if(user != null) {
            parameter.getEntity().setOperatorId(user.getId().toString());
            parameter.getEntity().setConfirmerId(user.getId());
        }
        if(company != null){
            parameter.getEntity().setRegionId(company.getRegionId());

        }
        if(parameter.getEntity().getId() == null)
            parameter.getEntity().setState(0L);
        else
            parameter.getEntity().setState(1L);
        return parameter;

    }

}
